$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/buserinfo/list',
        datatype: "json",
		async:false,
		colModel: [
			{ label: '用户编号', name: 'userId', index: 'user_id',align: "center", width: 50, key: true,formatter:function(value,options,rowData){
					let mainUserId = rowData["mainUserId"];
					let content = "<p><a  onclick='update("+value+")'>"+value+"</a></p>";
					if (mainUserId) {
						return content + "<p style='font-size: 8px; color: lightgrey'>主用户</p>";
					} else {
						return content;
					}
					/*return "<p><a  onclick='update("+value+")'>"+value+"</a></p>"
						+"<a onclick='updateMainUser("+value+")' style='font-size: 8px; color: lightgrey'>朔源</a>";*/
				}
			},
			{ label: '主用户编号', name: 'mainUserId', index: 'mainUserId',align: "center", width: 80, hidden: true },
			{ label: '用户昵称', name: 'nickName', index: 'nick_name',align: "center", width: 80 },
			{
				label: '微信昵称', name: 'userName', index: 'user_name', align: "center", width: 80,
				formatter: function (value, options, rowData) {
					let userId = rowData["userId"];
					return "<a onclick = 'vm.updateUserName(" + userId + ")' style='cursor: pointer'>" + value + "</a>";
				}
			},
			/*{ label: '关注品牌', name: 'brandName', index: 'brandName',align: "center", width: 80 },*/
			{ label: '关注行业', name: 'articleTypeName', index: 'articleTypeName',align: "center", width: 80 },
			{ label: '用户头像', name: 'avatarUrl', index: 'avatar_url', width: 80,align: "center", sortable: false, editable: false, formatter: function (value,options,rowData) {
					var url="https://lktvtool.oss-cn-shenzhen.aliyuncs.com/icon/236A5FF0-52DE-4644-B66C-E9555C97693D.png";
					if(value==null || value==""){
						return"<img src='" + url + "' width='60' />";
					}else {
						return "<img src='" + value + "' width='60' />";
					}
				}},
			{ label: '邀请人数', name: 'refererTotal',dataType: "int", sortable: true, index: 'referer_total',align: "center", width: 80 ,formatter:function(value,options,rowData){
					var userId=rowData["userId"];
					return "<a  onclick='vm.referer("+userId+")'>"+value+"</a>";
				}
			},
			{ label: '文章分享数', name: 'shareTotal',dataType: "int", sortable: true, index: 'share_total',align: "center", width: 80 },
			{ label: '总返利', name: 'cumulativeIncome',dataType: "int", sortable: true, index: 'cumulativeIncome',align: "center", width: 80 },
			{ label: '待提现', name: 'waitIncome',dataType: "int", sortable: true, index: 'waitIncome',align: "center", width: 80},
			{ label: '推荐人', name: 'referer', index: 'referer',align: "center", width: 80 ,formatter:function(value,options,rowData){
                if( value>0 ){
                    return "<a  onclick='update("+value+")'>"+value+"</a>";
                }else{
                    return '';
                }
            }
            },
			{ label: '会员状态', name: 'vipStatus', index: 'vip_status',align: "center", width: 80 ,formatter:function(value,options,rowData){
					if( value===1 ){
						return "<p style='color: #1AE61A'>" + '会员' + "</>";;
					}else{
						return '非会员';
					}
				}
			},
			{ label: '公众号关注状态', name: 'concernStatus', index: 'concern_status',align: "center", width: 80 ,formatter:function(value,options,rowData){
					if( value===1 ){
						return "<p style='color: #0997F7'>" + '已关注' + "</p>";
					}else{
						let unsubscribeTime = rowData["unsubscribeTime"];
						if(unsubscribeTime==null){
							return "<p style='color: #888888'>" + '未关注' + "</p>";
						}else {
							return "<p style='color: #FF0000'>" + '已取关'+"</p>" +unsubscribeTime ;
						}
					}
				}
			},
            { label: '公众号标识', name: 'gzhCode', index: 'gzh_code',align: "center", width:60, hidden: true },
            { label: '公众号', name: 'gzhName', index: 'gzh_name',align: "center", width:60, formatter:function(value,options,rowData){
            		let userId = rowData["userId"];
            		let userName = rowData["nickName"];
            		let gzhCode = rowData["gzhCode"];
            		let vipStatus = rowData["vipStatus"];
            		if ((gzhCode == "prodgjhkpt" || gzhCode == "back_zkt") && vipStatus == 0) {// 共建获客平台
            			return "<p>"+value+"</p><a onclick='vm.giveAYearVip("+userId+",\""+userName+"\")'>送一年</a>";
					} else {
						return "<p>"+value+"</p>";
					}
				}
			},
			{ label: '关注时间', name: 'subscribeTime', index: 'subscribe_time',align: "center", width: 80 },
			{ label: '黑名单操作', name: 'blockState', index: 'block_state',align: "center", width: 80 ,formatter:function(value,options,rowData){
					var userId=rowData["userId"];
					if( value===0 ){
						return "<input type=\"button\" class=\"btn btn-primary\" value='拉黑' onclick='vm.block("+userId+")'/>";
					}else{
						return "<input type=\"button\" class=\"btn btn-warning\" value='移出' onclick='vm.cancelblock("+userId+")'/>";
					}
				}
			},
        ],
		viewrecords: true,
		height: "100%",
		rowNum: 8,
		rowList : [8,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
		postData:{"user_id":vm.q.user_id,"nick_name": vm.q.nick_name,"user_name":vm.q.user_name,"referer":vm.q.referer,"brandName":vm.q.brandName,"articleTypeName":vm.q.articleTypeName,"userIds":vm.q.userIds,"concernStatus":vm.q.concernStatus,"gzhCode":vm.q.gzhCode,"brandId":vm.q.brandId,"vipStatus":vm.q.vipStatus,"beginConcernDate":vm.q.beginConcernDate,"endConcernDate":vm.q.endConcernDate},
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });

	$.ajax({
		type: "POST",
		url: baseURL + 'sys/buserinfo/getUserGzhList',
		contentType: "application/json",
		success: function(r){
			if(r.code==0){
				//vm.bbrandinfo=r.brandInfo;
				$("#selectUserGzhList").append(
					"<option value=''>全部平台</option>");
				for(var i=0;i<r.userGzhList.length;i++){
					$("#selectUserGzhList").append(
						"<option value=" + r.userGzhList[i].gzhCode +">"+ r.userGzhList[i].gzhName+"</option>");
				}
			}
		}
	});


	$.ajax({
			type: "POST",
			url: baseURL + 'sys/bbrandinfo/queryAll',
			contentType: "application/json",
			success: function(r){
				if(r.code==0){
					//vm.bbrandinfo=r.brandInfo;
					for(var i=0;i<r.brandInfo.length;i++){
						$("#brandName").append(
							"<option value=" + r.brandInfo[i].brandName +">"+"</option>");
					}
				}
			}
		});
	vm.initSizeSubUser();
	$(window).resize(function(){
		vm.resizeSubUser("jqGridSubUserInfo");
	});
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
			user_id:null,
			nick_name: null,
			user_name: null,
			referer:null,
			brandName:null,
			brandId:null,
			articleTypeName: null,
			userIds:null,
			concernStatus:1,
			vipStatus: '',
			gzhCode:"",
			blockState:"",
			beginConcernDate:null,
			endConcernDate:null
		},
		showList: true,
		addUser: true,
		title: null,
		bUserInfo: {},
		bUserInfoNot:{},
		obj:[],
		backStatus:0,
		id:0,
		showAll:false,
		headImgUrl:"https://lktvtool.oss-cn-shenzhen.aliyuncs.com/icon/236A5FF0-52DE-4644-B66C-E9555C97693D.png",
		width: null,
		height: null,
		layero: null,
		brandPostLayero: null,
		shieldFlag: false,
		bUserBrandInfo: {},
		brandPostIndex: null,
		standardWidth: 300, // 用户品牌海报单张图片的显示宽度
		brandPosterMaxCount: 3, // 用户品牌海报允许设置的最大数量
	},
	methods: {
		getSubordinate: function () {
			let userIds = $("#userId").val();
			if(userIds == null){
				return ;
			}

			$.ajax({
				type: "POST",
				url: baseURL + "sys/buserinfo/getSubordinate",
				contentType: "application/json",
				data: JSON.stringify(userIds),
				success: function(r){
					if(r.code == 0){
						alert('操作成功', function(index){
							$("#jqGrid").trigger("reloadGrid");
							console.info(r);
							// vm.bUserInfo.queryInWanted =true;
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		addWantedUser: function () {
			let userIds = $("#userId").val();
			if (userIds == null) {
				return;
			}

			confirm('确定要把该用户放入通缉名单中？', function () {
				$.ajax({
					type: "POST",
					url: baseURL + "sys/buserinfo/addWantedUser",
					contentType: "application/json",
					data: JSON.stringify(userIds),
					success: function (r) {
						if (r.code == 0) {
							alert('操作成功', function (index) {
								$("#jqGrid").trigger("reloadGrid");
								vm.bUserInfo.queryInWanted = true;
							});
						} else {
							alert(r.msg);
						}
					}
				});
			});
		},
		/**
		 * 屏蔽或恢复用户在文章底部的"换成我的"的功能
		 */
		shieldUserCopy: function () {
			debugger
			if (vm.shieldFlag) {
				// 删除操作
				$.ajax({
					type: "POST",
					url: baseURL + "sys/busershield/deleteByUserId/" + vm.bUserInfo.userId,
					contentType: "application/json",
					success: function(r){
						if(r.code == 0){
							alert("恢复成功");
							$("#userShield").val("屏蔽<换成我的>")
							$("#userShield").removeClass("btn-primary");
							$("#userShield").addClass("btn-danger");
							vm.shieldFlag = false;
						}else{
							alert(r.msg);
						}
					}
				});
			} else {
				// 添加操作
				let param = {userId: vm.bUserInfo.userId, gzhCode: vm.bUserInfo.gzhCode};
				$.ajax({
					type: "POST",
					url: baseURL + "sys/busershield/save",
					contentType: "application/json",
					data: JSON.stringify(param),
					success: function(r){
						if(r.code == 0){
							alert("屏蔽成功");
							$("#userShield").val("恢复<换成我的>")
							$("#userShield").removeClass("btn-danger");
							$("#userShield").addClass("btn-primary");
							vm.shieldFlag = true;
						}else{
							alert(r.msg);
						}
					}
				});
			}
		},
		updateUserName: function (userId) {
			var userIds = userId;
			if(userIds == null){
				return ;
			}

			$.ajax({
				type: "POST",
				url: baseURL + "sys/buserinfo/updateUserName",
				contentType: "application/json",
				data: JSON.stringify(userIds),
				success: function(r){
					if(r.code == 0){
						alert('操作成功', function(index){
							$("#jqGrid").trigger("reloadGrid");
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		getHeadImgUrl: function () {
			let userIds = $("#userId").val();
			if(userIds == null){
				return ;
			}

			$.ajax({
				type: "POST",
				url: baseURL + "sys/buserinfo/getHeadImgUrl",
				contentType: "application/json",
				data: JSON.stringify(userIds),
				success: function(r){
					if(r.code == 0){
						alert('操作成功', function(index){
							$("#headImgUrl").attr("src", r.headImgUrl);
							$("#userSubscribeScene").html("用户关注的渠道来源: [" + r.subscribeScene + "]");
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		query: function () {
            vm.showList = true;
			// vm.q.brandName=$("#brandNames").val();
			vm.q.articleTypeName=$("#articleTypeName").val();

			// 参数校验
			debugger
			if (vm.q.beginConcernDate && vm.q.endConcernDate) {
				if (new Date(vm.q.beginConcernDate) > new Date(vm.q.endConcernDate)) {
					alert("关注时间的开始日期不能大于结束日期");
					return;
				}
			}
            $("#jqGrid").jqGrid('setGridParam',{
				postData:{"user_id":vm.q.user_id,"nick_name": vm.q.nick_name,"user_name":vm.q.user_name,"referer":vm.q.referer,"brandName":vm.q.brandName,"articleTypeName":vm.q.articleTypeName,"userIds":vm.q.userIds,"concernStatus":vm.q.concernStatus,"gzhCode":vm.q.gzhCode,"brandId":vm.q.brandId,"vipStatus":vm.q.vipStatus,"beginConcernDate":vm.q.beginConcernDate,"endConcernDate":vm.q.endConcernDate},
                page:1
            }).trigger("reloadGrid");

			$.ajax({
				type: "POST",
				// async:false,
				async: true,
				url: baseURL + 'sys/buserinfo/queryUserVitalByGzh',
				contentType: "application/json",
				data: JSON.stringify({'gzhCode':vm.q.gzhCode}),
				success: function(r){
					if(r.code==0 && r.vital!=null){
						// $("#userCount").html(r.vital.userCount);
						// $("#jtxzCount").html(r.vital.jtxzCount);
						// $("#ztxzCount").html(r.vital.ztxzCount);
						// $("#yxhyCount").html(r.vital.yxhyCount);
						// $("#jtzfhyCount").html(r.vital.jtzfhyCount);
						// $("#ztzfhyCount").html(r.vital.ztzfhyCount);
						$("#jtgzCount").html(r.vital.jtgzCount+" / "+r.vital.gzCount);
						// $("#gzCount").html(r.vital.gzCount);
						$("#jtqgCount").html(r.vital.jtqgCount+" / "+r.vital.qgCount);
						// $("#qgCount").html(r.vital.qgCount);

						$("#d1hyCount").html(r.vital.d1hyCount);
						$("#d3hyCount").html(r.vital.d3hyCount);

						$("#gzhljgzCount").html(r.vital.gzhljgzCount);
						$("#gzhxzgzCount").html(r.vital.gzhxzgzCount);
						$("#gzhqxgzCount").html(r.vital.gzhqxgzCount);
						$("#gzhjgzCount").html(r.vital.gzhjgzCount);

						$("#gzhS0Count").html(r.vital.gzhS0Count);
						$("#gzhS1Count").html(r.vital.gzhS1Count);
						$("#gzhS17Count").html(r.vital.gzhS17Count);
						$("#gzhS30Count").html(r.vital.gzhS30Count);
					}
				}
			});

		},
		cancelUser:function(){
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			vm.q.concernStatus=0;
			$("#jqGrid").jqGrid('setGridParam',{
				postData:{'user_id':vm.q.user_id,'nick_name': vm.q.nick_name,'referer':vm.q.referer,"concernStatus":vm.q.concernStatus,'gzhCode':vm.q.gzhCode,'blockState':vm.q.blockState,'brandName':vm.q.brandName,"articleTypeName":vm.q.articleTypeName},
				page:page
			}).trigger("reloadGrid");
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.bUserInfo = {};
		},
		userAdd: function(){
			vm.bUserInfo = {};
			layer.open({
				type: 1,
				title: '新增',
				maxmin: true,
				shadeClose: true, //点击遮罩关闭层
				area : ['520px' , '450px'],
				content: $("#insert").html()
			});
		},
		update: function (event) {
			var userId = getSelectedRow();
			if(userId == null){
				return ;
			}
			vm.showList = false;
			$("#vip").find("option[value='" + '4' + "']").attr("selected", true);
            vm.title = "修改";
            vm.getInfo(userId)
		},
		saveOrUpdate: function (event) {
			debugger;
			var vipRank=$('#vip option:selected').val();
			vm.bUserInfo.vipRank=vipRank;
			vm.bUserInfo.vipStatus=$('#vipStatus option:selected').val();

			if(vm.bUserInfo.giveType==1 && vm.bUserInfo.giveVipDate==null ){
				alert('请选择赠送日期!');
				return ;
			}

			if(vm.bUserInfo.giveType==2 && (vm.bUserInfo.vipRank==4)){
				alert('请选择赠送时长!');
				return ;
			}

			var url = vm.bUserInfo.userId == null ? "sys/buserinfo/save" : "sys/buserinfo/update";

			var strBrandNames="";
            if($(".pBrandName").length>0){
                $(".pBrandName").each(function(){
                    strBrandNames=strBrandNames+","+$(this).attr("value");
                });
                strBrandNames=strBrandNames.substring(1);
            }

			var strArticleTypeNames="";
			if($(".pArticleTypeName").length>0){
				$(".pArticleTypeName").each(function(){

					strArticleTypeNames=strArticleTypeNames+","+$(this).attr("value");
				});
				strArticleTypeNames=strArticleTypeNames.substring(1);
			}
            vm.bUserInfo.brandName=strBrandNames;
			vm.bUserInfo.articleTypeName=strArticleTypeNames;
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data:JSON.stringify(vm.bUserInfo),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							if(vm.id!=0) {
								update(vm.id);
							}else {
								vm.reload();
							}
						});
					}else{
						alert(r.msg);
					}
				}
			});

		},
		/**
		 * 赠送一年 VIP (只针对公众号[共建获客平台])
		 * @param userId 用户Id
		 * @param userId 用户昵称
		 */
		giveAYearVip: function(userId, userName) {
			if (userId && userId > 0) {
				//

				confirm("确定要为用户【"+userName+"】赠送一年会员吗？", function () {
					$.ajax({
						type: "POST",
						url: baseURL + "sys/buserinfo/giveAYearVip/" + userId,
						contentType: "application/json",
						success: function(r){
							if(r.code === 0){
								alert('操作成功', function(index){
									vm.reload();
								});
							}else{
								alert(r.msg);
							}
						}
					});
				});
			}
		},
		savebUserInfoNot: function (event) {
			if($("#remarksContent").val() == ''){
				alert("备注不能为空");
				return false;
			}
			vm.bUserInfoNot.buserinfoId = $("#userId").val();
			$.ajax({
				type: "POST",
				url: baseURL + "sys/buserinfo/save2",
				contentType: "application/json",
				data:JSON.stringify(vm.bUserInfoNot),
				success: function(r){
					if(r.code === 0){
						alert('备注提交成功', function(index){
							// vm.reload();

							var buserinfo_id = $("#userId").val();
							console.log(buserinfo_id);
							if(buserinfo_id == null){
								return ;
							}
							$.ajax({
								type: "POST",
								async: true,
								url: baseURL + "sys/buserinfo/infonot",
								contentType: "application/json",
								data: JSON.stringify(buserinfo_id),
								success: function(r){
									console.log(r.listnot);
									if(r.code == 0 && r.listnot!=null){
										console.log(r);
										vm.obj = r.listnot;
									}else{
										alert(r.msg);
									}
								},
								complete: function() {
									//请求完成的处理
									console.log("请求完成！");
								},
								error: function() {
									//请求出错处理
									console.log("请求出错！");
								}
							});
						});

						vm.bUserInfoNot.remarksContent="";
					}else{
						alert(r.msg);
					}
				}
			});
		},
		lookbUserInfoNot: function (event) {
			var buserinfo_id = $("#userId").val();
			console.log(buserinfo_id);
			if(buserinfo_id == null){
				return ;
			}
			$.ajax({
				type: "POST",
				url: baseURL + "sys/buserinfo/infonot",
				contentType: "application/json",
				data: JSON.stringify(buserinfo_id),
				success: function(r){
					console.log(r.listnot);
					if(r.code == 0 && r.listnot!=null){
						console.log(r);
						vm.obj = r.listnot;
					}else{
						alert(r.msg);
					}
				},
				complete: function() {
					//请求完成的处理
					console.log("请求完成！");
				},
				error: function() {
					//请求出错处理
					console.log("请求出错！");
				}
			});
		},
		updateCensus: function (event) {

			$.ajax({
				type: "POST",
				url: baseURL + "sys/buserinfo/updateCensus",
				contentType: "application/json",
				success: function(r){
					if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		createCouponLink:function (event) {
			debugger;

			var url ="sys/buserinfo/createCouponLink";

			$.ajax({
				type: "POST",
				url: baseURL + url,
				contentType: "application/json",
				data:JSON.stringify(vm.bUserInfo),
				success: function(r){
					if(r.code === 0){
						$('#coupon_link').val(r.couponUrl);
						var link=document.getElementById("coupon_link");

						link.select(); // 选择对象

						document.execCommand("Copy"); // 执行浏览器复制命令

						alert("已复制，可贴粘。");
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var userIds = getSelectedRows();
			if(userIds == null){
				return ;
			}

			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "sys/buserinfo/delete",
                    contentType: "application/json",
				    data: JSON.stringify(userIds),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(userId){
			debugger;

			$("#vip").empty();
			$("#vipStatus").empty();
			$.get(baseURL + "sys/buserinfo/info/"+userId, function(r){
				//console.log("用户信息：" + r.bUserInfo);
				if (r.bUserInfo) {
					vm.showList = false;
				} else {
					return;
				}
                vm.bUserInfo = r.bUserInfo;
				$("#vip").append(
						"<option value=" + 4 + ">" + '请选择' + "</option>");
                $("#vip").append(
                    "<option value=" + 30 + ">" + '一个月' + "</option>");
                $("#vip").append(
                        "<option value=" + 90 + ">" + '三个月' + "</option>");
                $("#vip").append(
						"<option value=" + 180 + ">" + '半年' + "</option>");
				$("#vip").append(
						"<option value=" + 365 + ">" + '一年' + "</option>");
                $("#vip").append(
                        "<option value=" + 730 + ">" + '二年' + "</option>");
				$("#vip").append(
						"<option value=" + 1095 + ">" + '三年' + "</option>");
                $("#vip").append(
                    "<option value=" + 1825 + ">" + '五年' + "</option>");
                $("#vip").append(
                    "<option value=" + 3650 + ">" + '十年' + "</option>");
                $("#vip").append(
                    "<option value=" + 36500 + ">" + '一百年' + "</option>");
				$("#vip").find("option[value='" + 4 + "']").attr("selected", true);
				var status=vm.bUserInfo.vipStatus;

				vm.bUserInfo.giveType=0;
				if(status==""||status==null){
					status=0;
				}
				$("#vipStatus").append(
					"<option value=" + 1 + ">" + '是' + "</option>");
				$("#vipStatus").append(
					"<option value=" + 0 + ">" + '否' + "</option>");
				$("#vipStatus").find("option[value='" + status + "']").attr("selected", true);

				/*品牌*/
                $(".pBrandName").remove();
				if(vm.bUserInfo.brandName){
                    var bns= new Array(); //定义一数组
                    bns=vm.bUserInfo.brandName.split(","); //字符分割
                    for (i=0;i<bns.length ;i++ ) {
                        var index=genID(6);//获取6位随机ID
                        $("#selectBrandNameList").append(
                            "<p class='pBrandName' id='pBrandName"+index+"' value='"+bns[i]+"'>"+bns[i]+"&nbsp;<a href='javascript:void(0);' onclick='delBrand("+index+")'>删除</a></p>");
                    }
                }
				/*分类*/
				$(".pArticleTypeName").remove();
				if(vm.bUserInfo.articleTypeName){
					var ats= new Array(); //定义一数组
					ats=vm.bUserInfo.articleTypeName.split(","); //字符分割
					for (i=0;i<ats.length ;i++ ) {
						var index=genID(6);//获取6位随机ID
						$("#selectArticleTypeNameList").append(
							"<p class='pArticleTypeName' id='pArticleTypeName"+index+"' value='"+ats[i]+"'>"+ats[i]+"&nbsp;<a href='javascript:void(0);' onclick='delArticle("+index+")'>删除</a></p>");
					}
				}
            });
		},
		reload: function (event) {
			debugger;
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
				postData:{'user_id':vm.q.user_id,'nick_name': vm.q.nick_name,'referer':vm.q.referer},
                page:page
            }).trigger("reloadGrid");
		},
		encode:function(input){
			var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
			var output = "";
			var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
			var i = 0;
			input = vm._utf8_encode(input);
			while (i < input.length) {
				chr1 = input.charCodeAt(i++);
				chr2 = input.charCodeAt(i++);
				chr3 = input.charCodeAt(i++);
				enc1 = chr1 >> 2;
				enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
				enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
				enc4 = chr3 & 63;
				if (isNaN(chr2)) {
					enc3 = enc4 = 64;
				} else if (isNaN(chr3)) {
					enc4 = 64;
				}
				output = output +
					_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
					_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
			}
			return output;
		},
		_utf8_encode:function(string){
			var input=string.toString();
			input = input.replace(/\r\n/g,"\n");
			var utftext = "";
			for (var n = 0; n < input.length; n++) {
				var c = input.charCodeAt(n);
				if (c < 128) {
					utftext += String.fromCharCode(c);
				} else if((c > 127) && (c < 2048)) {
					utftext += String.fromCharCode((c >> 6) | 192);
					utftext += String.fromCharCode((c & 63) | 128);
				} else {
					utftext += String.fromCharCode((c >> 12) | 224);
					utftext += String.fromCharCode(((c >> 6) & 63) | 128);
					utftext += String.fromCharCode((c & 63) | 128);
				}

			}
			return utftext;
		},
		referer:function (e) {
			e = vm.encode(e);
			var url="http://vtoolcps.lktsell.cn/?user_id="+e;
			layer.open({
				type: 2,
				title: '已邀请',
				maxmin: true,
				shadeClose: true, //点击遮罩关闭层
				area : ['420px' , '650px'],
				content: "http://vtoolcps.lktsell.cn/?user_id="+e
			});
		},
		block:function (userId) {
			confirm('确定要拉黑该用户吗？', function(){
				$.ajax({
					type: "POST",
					url: baseURL + "sys/buserinfo/block",
					contentType: "application/json",
					data: JSON.stringify(userId),
					success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		cancelblock:function (userId) {
			confirm('确定要把该用户移动黑名单？', function(){
				$.ajax({
					type: "POST",
					url: baseURL + "sys/buserinfo/cancelblock",
					contentType: "application/json",
					data: JSON.stringify(userId),
					success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getSubUser: function(userId) {
			// 1、参数校验
			if (userId == null) {
				return;
			}
			var selector = "jqGridSubUserInfo";
			// 2、清空数据
			$("#"+selector).jqGrid("clearGridData")
			// 3、加载数据
			vm.getSubUserInfo(userId, selector, 2);
			// 4、弹窗
			vm.layerOpenSubUser();
			// 5、重新加载数据
			vm.reloadRelation(userId, selector);
		},
		layerOpenSubUser: function() {
			layer.open({
				type: 1,
				title: ['用户下级(二级)', 'font-weight: bold'],
				area: [vm.width+'px', vm.height+'px'],
				shadeClose: true,
				scrollbar: false,
				content: $('#layerSubUserInfo'),
				success: function (layero, index) {
					vm.layero = layero;
				}
			});
		},
		getSubUserInfo: function(userId, selector, type) {
			let selected = $("#"+selector);
			selected.jqGrid({
				url: baseURL + 'sys/buserinfo/getSubUser',
				datatype: "json",
				colModel: [
					{label: '用户编号', name: 'userId', index: 'user_id', align: "center", width: 40,
						formatter: function(value,options,rowData) {
							if (type == 1) {
								return "<a onclick='vm.getSubUser("+value+")'>"+value+"</a>";
							} else if (type == 2) {
								return value;
							}
						}
					},
					{label: '用户昵称', name: 'nickName', index: 'nick_name', align: "center", width: 80},
					{
						label: '用户头像',
						name: 'avatarUrl',
						index: 'avatarUrl',
						width: 60,
						align: "center",
						sortable: false,
						editable: false,
						formatter: function (value, options, rowData) {
							var url = "https://lktvtool.oss-cn-shenzhen.aliyuncs.com/icon/236A5FF0-52DE-4644-B66C-E9555C97693D.png";
							if (value == null || value == "") {
								return "<img src='" + url + "' width='60' height='60' />";
							} else {
								return "<img src='" + value + "' width='60' height='60' />";
							}
						}
					},
					{ label: '关注品牌', name: 'brandName', index: 'brandName',align: "center", width: 80 },
					{ label: '会员状态', name: 'vipStatus', index: 'vip_status',align: "center", width: 60 ,formatter:function(value,options,rowData){
							if( value===1 ){
								return "<p style='color: #1AE61A'>" + '会员' + "</>";;
							}else{
								return '非会员';
							}
						}
					},
					{ label: '公众号关注状态', name: 'concernStatus', index: 'concern_status',align: "center", width: 80 ,formatter:function(value,options,rowData){
							if( value===1 ){
								return "<p style='color: #0997F7'>" + '已关注' + "</p>";
							}else{
								let unsubscribeTime = rowData["unsubscribeTime"];
								if(unsubscribeTime==null){
									return "<p style='color: #888888'>" + '未关注' + "</p>";
								}else {
									return "<p style='color: #FF0000'>" + '已取关'+"</p>" +unsubscribeTime ;
								}
							}
						}
					},
					{ label: '公众号', name: 'gzhName', index: 'gzh_name',align: "center", width:60 },
					{ label: '关注时间', name: 'subscribeTime', index: 'subscribe_time',align: "center", width: 80 },
				],
				height: $(window).height() - 136,
				rowNum: 10000,
				rownumbers: true,
				rownumWidth: 50,
				autowidth: true,
				multiselect: false,
				jsonReader: {
					root: "subUserList"
				},
				postData: {'userId': userId},
				gridComplete: function () {
					if (type == 2) {
						vm.setGridSize(selector);
					}
					//隐藏grid底部滚动条
					selected.closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
				}
			});
		},
		reloadRelation: function (userId, selector) {
			$("#"+selector).jqGrid('setGridParam',{
					postData: {'userId': userId}
				}).trigger("reloadGrid");
		},
		initSizeSubUser: function() {
			// 初始化宽高值，用于定义弹窗的大小
			vm.width = $(window).width() - 500;
			vm.height = $(window).height() - 120;
		},
		resizeSubUser: function (selector) {
			vm.initSizeSubUser();

			// layer 自适应
			if (vm.layero) {
				vm.layero.css("width", vm.width + "px");
				vm.layero.css("height", vm.height + "px");
				vm.setGridSize(selector);
			}
		},
		setGridSize: function (selector) {
			$("#"+selector).jqGrid("setGridWidth", vm.width - 18);
			$("#"+selector).jqGrid("setGridHeight", vm.height - 84);
		},
		updateUserBrandPoster: function (id) {
			$.get(baseURL+"sys/buserbrandinfo/simplyInfo/"+id, function (r) {
				if (r.code == 0) {
					vm.bUserBrandInfo = r.bUserBrandInfo;
					// 先清除数据
					$("#brandPosterList").empty();

					let len = 0;
					// 多张海报图显示，按需增加宽度
					if (vm.bUserBrandInfo.brandPoster && vm.bUserBrandInfo.brandPoster != '') {
						// 海报图片，多个是用逗号隔开
						let brandPoster = vm.bUserBrandInfo.brandPoster;
						// 分割成数组
						let brandPosterArray = brandPoster.split(",");
						// 图片张数
						len = brandPosterArray.length;
						if (len > 0) {
							// 循环创建
							for (let i = 0; i < len && i < vm.brandPosterMaxCount; i++) {
								// div 左浮动
								let div = vm.createBrandImgObject(brandPosterArray[i]);
								$("#brandPosterList").append(div);
							}
						}
					}
					// 如果海报图片小于三张，则给一个空的 img 对象，用于添加图片
					if (len < vm.brandPosterMaxCount) {
						$("#brandPosterList").append(vm.createBrandImgObject(""));
					}
					vm.showLayerUserBrandPoster();
				} else {
					alert(r.msg);
				}
			});
		},
		/**
		 * // 构建 div 封装图片，设置为图片左浮动
		 * @param url 图片路径
		 * @returns {string}
		 */
		createBrandImgObject: function (url) {
			return "<div style='width: 280px; float: left; margin: 10px'>"+
				"<input type='button' class='btn btn-danger' value='删除' style='float: right' onclick='vm.deleteBrandPoster(this)' />"+
				"<img src='"+url+"' width='280px' height='280px' alt='' style='margin: 10px 0px' />"+
				"<input type='file' accept='image/*' onchange='insertBrandPosterImg(this,\"userLongTermQrCodeImg\")' />"+
				"</div>";
		},
		showLayerUserBrandPoster: function () {
			let total = vm.standardWidth * vm.brandPosterMaxCount;
			let brandPostIndex = layer.open({
				type: 1,
				title: '修改用户的品牌海报(最多上传'+vm.brandPosterMaxCount+'张)',
				area: [total+'px', '500px'],
				shadeClose: true,
				content: $('#layerUserBrandPoster'),
				success: function (layero, index) {
					vm.brandPostLayero = layero;
				}
			});
			vm.brandPostIndex = brandPostIndex;
		},
		/**
		 * 删除用户品牌海报
		 * 如果图片数量为1，则直接去掉 src 属性
		 * 如果图片数量大于 1，且小于等于3,则移除 div
		 * @param obj
		 */
		deleteBrandPoster: function(obj) {
			let url = $(obj).next().attr("src");
			if (!url || url == '') {
				alert("请先上传海报图片！");
				return;
			}

			layer.confirm("您确定要删除该海报吗？", function (index) {
				// 获取父元素 div
				let div = $(obj).parent();
				$(div).remove();// 移除该 div

				// 移除后，如果最后一个 img 有图片，则新增一个空的 div 在最后面
				let imgLength = $("#brandPosterList img").length;// 当前 img 数量
				console.log("当前 img 个数为："+imgLength);
				let img = $("#brandPosterList img").eq(imgLength - 1);
				let url = $(img).attr("src");

				if (url && url != '') {
					// 新增一个空的 div,在最后面
					$("#brandPosterList").append(vm.createBrandImgObject(""));
				}
				layer.close(index);
			});
		},
		closeLayerUserBrandPoster: function () {
			if (vm.brandPostIndex) {
				layer.close(vm.brandPostIndex);
			}
		},
		saveUserBrandPoster: function () {
			// 当前 img 数量
			let imgLength = $("#brandPosterList img").length;
			console.log("当前 img 个数为："+imgLength);

			if (!imgLength || imgLength == 0) {
				alert("请上传图片");
				return;
			}

			let brandPosterUrls = "";
			// 遍历图片
			for (let i = 0; i < imgLength; i++) {
				let img = $("#brandPosterList img")[i];
				let url = $(img).attr("src");
				if (url && url != '') {
					brandPosterUrls += url + ",";
				}
			}
			// 去掉最后一个逗号
			brandPosterUrls = brandPosterUrls.substring(0, brandPosterUrls.length - 1);
			console.log("保存的海报集合："+brandPosterUrls);
			vm.bUserBrandInfo.brandPoster = brandPosterUrls;

			$.ajax({
				type: "POST",
				url: baseURL + "sys/buserbrandinfo/updateUserBrandPoster",
				contentType: "application/json;charset=utf-8",
				data: JSON.stringify(vm.bUserBrandInfo),
				success: function (r) {
					if (r.code == 0) {
						vm.closeLayerUserBrandPoster();
						// 刷新列表
						reloadBrandPoster();
						alert("保存成功");
					} else {
						alert(r.msg);
					}
				}
			});
		},
		resetCondition: function () {
			vm.q.user_id = null;
			vm.q.nick_name = null;
			vm.q.referer = null;
			vm.q.gzhCode = "";
			vm.q.blockState = "";
			// $("#brandNames").val("");
			$("#articleTypeName").val("");
			vm.q.concernStatus = 1;
			vm.q.user_name = null;
			vm.q.vipStatus = "";
			vm.q.beginConcernDate = null;
			vm.q.endConcernDate = null;
		}
	}
});
function update(e) {
	//vm.showList = false;
	$("#vip").find("option[value='" + '4' + "']").attr("selected", true);
	vm.title = "修改";

	vm.getInfo(e)

	// 清空数据
	$("#userSubscribeScene").html();

	var buserinfo_id = e;
	console.log(buserinfo_id);
	if(buserinfo_id == null){
		return ;
	}
	$("#tab_currentUser").empty();
	$("#tab_currentUser").text("个人信息("+buserinfo_id+")");

	$.ajax({
		type: "POST",
		async: true,
		url: baseURL + "sys/buserinfo/infonot",
		contentType: "application/json",
		data: JSON.stringify(buserinfo_id),
		success: function(r){
			console.log(r.listnot);
			if(r.code == 0 && r.listnot!=null){
				console.log(r);
				vm.obj = r.listnot;
			}else{
				alert(r.msg);
			}
		},
		complete: function() {
			//请求完成的处理
			console.log("请求完成！");
		},
		error: function() {
			//请求出错处理
			console.log("请求出错！");
		}
	});
	// 1、用户上下级关系的数量
	$.ajax({
		type: "GET",
		url: baseURL + "sys/buserinfo/getSubUserCount/"+buserinfo_id,
		contentType: "application/json",
		success: function(r){
			let tab = $("#tab_subUser");
			tab.empty();
			if(r.code == 0){
				tab.text("上下级关系("+r.subUserCount+")");
			}else{
				tab.text("上下级关系(0)");
			}
		}
	});
	// 2、加入的团队的数量
	$.ajax({
		type: "GET",
		url: baseURL + "sys/bteamrelation/getUserTeamCount/"+buserinfo_id,
		contentType: "application/json",
		success: function(r){
			let tab = $("#tab_userTeam");
			tab.empty();
			if(r.code == 0){
				tab.text("加入的团队("+r.userTeamCount+")");
			}else{
				tab.text("加入的团队(0)");
			}
		}
	});
	// 3、微站文章的数量
	$.ajax({
		type: "GET",
		url: baseURL + "sys/barticleinfo/getUserArticleCount/"+buserinfo_id,
		contentType: "application/json",
		success: function(r){
			let tab = $("#tab_article");
			tab.empty();
			if(r.code == 0){
				tab.text("微站文章("+r.userArticleCount+")");
			}else{
				tab.text("微站文章(0)");
			}
		}
	});
	// 4、分享文章的数量
	$.ajax({
		type: "GET",
		url: baseURL + "sys/barticleinfo/getUserShareArticleCount/"+buserinfo_id,
		contentType: "application/json",
		success: function(r){
			let tab = $("#tab_shareArticle");
			tab.empty();
			if(r.code == 0){
				tab.text("分享文章("+r.userShareArticleCount+")");
			}else{
				tab.text("分享文章(0)");
			}
		}
	});
	// 5、浏览过的文章的数量
	$.ajax({
		type: "GET",
		url: baseURL + "sys/articlelookdetaillog/getUserLookCount/"+buserinfo_id,
		contentType: "application/json",
		success: function(r){
			let tab = $("#tab_scanArticle");
			tab.empty();
			if(r.code == 0){
				tab.text("浏览过的文章("+r.userLookCount+")");
			}else{
				tab.text("浏览过的文章(0)");
			}
		}
	});
	// 6、打卡明细的数量
	$.ajax({
		type: "GET",
		url: baseURL + "sys/buserinfo/getUserClockCount/"+buserinfo_id,
		contentType: "application/json",
		success: function(r){
			let tab = $("#tab_clock");
			tab.empty();
			if(r.code == 0){
				tab.text("打卡明细("+r.userClockCount+")");
			}else{
				tab.text("打卡明细(0)");
			}
		}
	});
	// 7、获取用户品牌海报的数量
	$.ajax({
		type: "GET",
		url: baseURL + "sys/buserbrandinfo/getUserBrandCount/"+buserinfo_id,
		contentType: "application/json",
		success: function(r){
			let tab = $("#tab_brandPoster");
			tab.empty();
			if(r.code == 0){
				tab.text("品牌海报("+r.userBrandCount+")");
			}else{
				tab.text("品牌海报(0)");
			}
		}
	});
	// 8、获取用户[他还关注了]的数量
	$.ajax({
		type: "GET",
		url: baseURL + "sys/busergroupopenid/getUserOtherFollowGzh/"+buserinfo_id,
		contentType: "application/json",
		success: function(r){
			let tab = $("#tab_otherFollowGzh");
			tab.empty();
			if(r.code == 0){
				tab.text("他还关注了("+r.userOtherFollowGzhCount+")");
			}else{
				tab.text("他还关注了(0)");
			}
		}
	});
	// 9、获取用户[关键词回复]的数量
	$.ajax({
		type: "GET",
		url: baseURL + "sys/keywordlog/getUserKeywordCount/"+buserinfo_id,
		contentType: "application/json",
		success: function(r){
			let tab = $("#tab_keyword");
			tab.empty();
			if(r.code == 0){
				tab.text("关键字回复("+r.userKeywordCount+")");
			}else{
				tab.text("关键字回复(0)");
			}
		}
	});
	// 10、获取用户[他添加了谁]的数量
	$.ajax({
		type: "GET",
		url: baseURL + "sys/bconnectionapplyinfo/getUserConnectionApplyCount/"+buserinfo_id,
		contentType: "application/json",
		success: function(r){
			let tab = $("#tab_connectionApply");
			tab.empty();
			if(r.code == 0){
				tab.text("他添加了谁("+r.userConnectionApplyCount+")");
			}else{
				tab.text("他添加了谁(0)");
			}
		}
	});
	// 99、获取用户是否屏蔽的文章"换成我的"的功能
	$.ajax({
		type: "GET",
		url: baseURL + "sys/busershield/userInfo/"+buserinfo_id,
		contentType: "application/json",
		success: function(r){
			if (r.code == 0) {
				if (r.bUserShield) {
					$("#userShield").val("恢复<换成我的>")
					$("#userShield").removeClass("btn-danger");
					$("#userShield").addClass("btn-primary");
					vm.shieldFlag = true;
				} else {
					$("#userShield").val("屏蔽<换成我的>")
					$("#userShield").removeClass("btn-primary");
					$("#userShield").addClass("btn-danger");
					vm.shieldFlag = false;
				}
			}
		}
	});
}

function genID(){
    return Math.floor(Math.random()*(999999-100000))+100000;
}
// function update(e) {
// 	vm.showList = false;
// 	$("#vip").find("option[value='" + '4' + "']").attr("selected", true);
// 	vm.title = "修改";
// 	var page = $("#jqGrid").jqGrid('getGridParam','page');
// 	$("#jqGrid").jqGrid('setGridParam',{
// 		postData:{'user_id':vm.q.user_id,'nick_name': vm.q.nick_name,'referer':vm.q.referer},
// 		page:page
// 	}).trigger("reloadGrid");
//
// }

function updateMainUser(userId) {
	if (!userId) {
		return;
	}

	// 根据该用户 ID 查找主用户 ID
	$.ajax({
		type: "POST",
		url: baseURL + "sys/buserinfo/mainUser/" + userId,
		contentType: "application/josn;charset=utf-8",
		success: function (r) {
			if (r.code == 0) {
				if (r.mainUserId) {
					update(r.mainUserId);
				} else {
					update(userId);
				}
			}
		}
	});
}
